<script setup lang="ts">
import { onMounted, reactive, ref, nextTick } from 'vue'
import {
  addOrUpdateRole,
  getAclByRole,
  getAllMenu,
  getRoleList,
  removeRole,
} from '@/api/acl/role/index.ts'
import { ElMessage } from 'element-plus'
import useStoreSetting from '@/store/modules/setting.ts'
const useSetting = useStoreSetting()
let currentPage = ref(1)
let pageSize = ref(5)
let total = ref()
const roleData = ref()
const searchValue = ref('')
const dialogFormVisible = ref(false)
const ruleFormRef = ref()
const roleParams = reactive<any>({
  roleName: '',
})
const drawer = ref(false)
onMounted(() => {
  getRole()
})
const getRole = async (pager = 1) => {
  currentPage.value = pager
  let res = await getRoleList(
    currentPage.value,
    pageSize.value,
    searchValue.value,
  )
  if (res.code === 200) {
    roleData.value = res.data.records
    total.value = res.data.total
  }
}
const handleSizeChange = () => {
  getRole()
}
const addRole = () => {
  dialogFormVisible.value = true
  Object.assign(roleParams, {
    roleName: '',
    id: 0,
  })
  nextTick(() => {
    ruleFormRef.value.clearValidate('roleName')
  })
}
const editRole = (row: any) => {
  dialogFormVisible.value = true
  Object.assign(roleParams, row)
  nextTick(() => {
    ruleFormRef.value.clearValidate('roleName')
  })
}

const deleteRoleById = async (id: number | string) => {
  let res: any = await removeRole(id)
  if (res.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    await getRole(
      roleData.value.length > 1 ? currentPage.value : currentPage.value - 1,
    )
  } else {
    ElMessage({
      type: 'error',
      message: '删除失败',
    })
  }
}
const treeData = ref([])
const selectTree = ref<any[]>([])
const assignAcl = async (row: any) => {
  Object.assign(roleParams, row)
  let res: any = await getAllMenu(roleParams.id)
  if (res.code === 200) {
    drawer.value = true
    treeData.value = res.data
    selectTree.value = filterTree(treeData.value, [])
  }
}
const filterTree = (allData: any, initArr: any) => {
  allData.forEach((item: any) => {
    if (item.select && item.level === 4) {
      initArr.push(item.id)
    }
    if (item.children && item.children.length > 0) {
      filterTree(item.children, initArr)
    }
  })
  return initArr
}
const search = () => {
  getRole()
  searchValue.value = ''
}
const reset = () => {
  useSetting.refresh = !useSetting.refresh
}
const validatorRoleName = (_: any, value: any, callBack: any) => {
  if (value.trim().length >= 2) {
    callBack()
  } else {
    callBack(new Error('职位名称至少两位'))
  }
}
const rules = {
  roleName: [{ required: true, trigger: 'blur', validator: validatorRoleName }],
}

const submitForm = async () => {
  await ruleFormRef.value.validate()
  let res: any = await addOrUpdateRole(roleParams)
  if (res.code == 200) {
    ElMessage({
      type: 'success',
      message: roleParams.id ? '更新成功' : '添加成功',
    })
    dialogFormVisible.value = false
    //再次获取全部的已有的职位
    await getRole(roleParams.id ? currentPage.value : 1)
  }
}
const tree = ref()
const cancelClick = () => {
  drawer.value = false
}
const confirmClick = async () => {
  drawer.value = false
  let arrKey = tree.value.getCheckedKeys()
  let prentArrKey = tree.value.getHalfCheckedKeys()
  let permissionId = arrKey.concat(prentArrKey)
  // console.log(roleParams.id, permissionId)
  let res: any = await getAclByRole(roleParams.id, permissionId)
  if (res.code == 200) {
    drawer.value = false
    window.location.reload()
    ElMessage({ type: 'success', message: '分配权限成功' })
  }
}
const defaultProps = {
  children: 'children',
  label: 'name',
}
</script>

<template>
  <el-card style="height: 70px">
    <el-form class="form">
      <el-form-item label="用户名:">
        <el-input placeholder="请输入用户名" v-model="searchValue"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          plain
          @click="search"
          :disabled="!searchValue"
        >
          搜索
        </el-button>
        <el-button plain @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card style="margin: 10px 0">
    <el-button type="success" plain @click="addRole" v-has="`btn.Role.add`">
      添加职位
    </el-button>
    <el-table border style="margin: 10px 0" :data="roleData">
      <el-table-column type="index" label="#" align="center"></el-table-column>
      <el-table-column label="ID" align="center" prop="id"></el-table-column>
      <el-table-column
        label="职位名称"
        align="center"
        prop="roleName"
      ></el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column label="操作" width="350px" align="center">
        <template #="{ row }">
          <el-button
            type="primary"
            plain
            icon="User"
            @click="assignAcl(row)"
            v-has="`btn.Role.assgin`"
          >
            分配权限
          </el-button>
          <el-button
            type="warning"
            plain
            icon="Edit"
            @click="editRole(row)"
            v-has="`btn.Role.update`"
          >
            编辑
          </el-button>
          <el-popconfirm
            :title="`你确定删除'${row.roleName}'这个角色吗？`"
            @confirm="deleteRoleById(row.id)"
            width="250"
          >
            <template #reference>
              <el-button
                type="danger"
                plain
                icon="Delete"
                v-has="`btn.Role.remove`"
              >
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 15]"
      layout="prev, pager, next, jumper,->,total, sizes"
      :total="Number(total)"
      @size-change="handleSizeChange"
      @current-change="getRole"
      :pager-count="7"
    />

    <el-dialog
      v-model="dialogFormVisible"
      :title="roleParams.id ? '编辑职位' : '添加职位'"
    >
      <el-form :model="roleParams" ref="ruleFormRef" :rules="rules">
        <el-form-item label="职位名称" prop="roleName">
          <el-input
            v-model="roleParams.roleName"
            placeholder="请输入职位名称"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <el-drawer v-model="drawer">
      <template #header>
        <h4>分配职位权限</h4>
      </template>
      <template #default>
        <el-tree
          ref="tree"
          :data="treeData"
          show-checkbox
          node-key="id"
          default-expand-all
          :default-checked-keys="selectTree"
          :props="defaultProps"
        />
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="cancelClick">取消</el-button>
          <el-button type="primary" @click="confirmClick">确认</el-button>
        </div>
      </template>
    </el-drawer>
  </el-card>
</template>

<style scoped lang="scss">
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
